const TronWeb = require('tronweb');
const fs = require('fs');
const path = require('path');

const config = require('./tronbox.js');
const shastaConfig = config.networks.shasta;
const contractData = JSON.parse(fs.readFileSync(path.join(__dirname, 'build/contracts/TRXBetLottery.json'), 'utf8'));

async function deploy() {
    const tronWeb = new TronWeb({ fullHost: shastaConfig.fullHost });
    
    console.log('🚀 部署合约到 Shasta 测试网...\n');
    
    // 检查连接和账户
    await tronWeb.isConnected();
    tronWeb.setPrivateKey(shastaConfig.privateKey);
    const account = tronWeb.defaultAddress.base58;
    const balance = await tronWeb.trx.getBalance(account);
    
    console.log(`账户: ${account} (${(balance / 1e6).toFixed(2)} TRX)\n`);
    
    // 准备参数
    const devWalletHex = tronWeb.address.toHex(account);
    const firstDeadline = Math.floor(Date.now() / 1000) + 3600;
    
    // 编码构造函数参数
    let bytecode = contractData.bytecode;
    if (bytecode.startsWith('0x')) bytecode = bytecode.slice(2);
    
    const param = tronWeb.utils.abi.encodeParams(['address', 'uint256'], [devWalletHex, firstDeadline.toString()]);
    const paramHex = param.startsWith('0x') ? param.slice(2) : param;
    const fullCode = bytecode + paramHex;
    
    console.log('创建部署交易...\n');
    
    // 直接使用 createSmartContract，传递 parameter 字段
    const tx = await tronWeb.transactionBuilder.createSmartContract({
        abi: contractData.abi,
        bytecode: bytecode,
        parameter: paramHex
    }, account);
    
    tx.feeLimit = shastaConfig.feeLimit;
    const signed = await tronWeb.trx.sign(tx);
    const result = await tronWeb.trx.sendRawTransaction(signed);
    
    console.log(`✅ 交易已提交: ${result}\n等待确认...`);
    
    for (let i = 0; i < 30; i++) {
        await new Promise(r => setTimeout(r, 2000));
        const info = await tronWeb.trx.getTransactionInfo(result).catch(() => null);
        if (info?.receipt?.result === 'SUCCESS' && info.contract_address) {
            const addr = tronWeb.address.fromHex(info.contract_address);
            console.log(`\n🎉 部署成功！`);
            console.log(`合约地址: ${addr}`);
            console.log(`https://shasta.tronscan.org/#/contract/${addr}`);
            return;
        }
    }
    
    throw new Error('确认超时，请查看交易状态');
}

deploy().catch(e => { console.error('❌ 失败:', e.message); process.exit(1); });

